package javango.forms.fields;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

import com.google.inject.Inject;

import javango.forms.widgets.ChoicesWidget;
import javango.forms.widgets.SelectWidget;
import javango.forms.widgets.Widget;
import javango.forms.widgets.WidgetFactory;

public class LongChoiceField extends javango.forms.fields.AbstractChoiceField<Long> {

	@Inject
	public LongChoiceField(WidgetFactory widgetFactory) {
		super(widgetFactory);
	}
	
	public LongChoiceField setChoices(Map<Long, String> choices) {
//		Map<String, String> stringChoices = new HashMap<String, String>();
//		for(Entry<Long, String> e : choices.entrySet()) {
//			stringChoices.put(e.getKey() == null ? null : e.getKey().toString(), e.getValue());
//		}
		return (LongChoiceField)super.setChoices(choices);
	}
	
	@Override
	protected Object clean(String value, Map<String, String> errors) {
		String v1 = (String)super.clean(value, errors);
		if (StringUtils.isEmpty(v1)) {
			return null;
		}
		
		try {
			return Long.valueOf(v1);
		} catch (NumberFormatException e) {
			errors.put(getName(), UNKNOWN_CHOICE_ERROR);
		}
		
		return null;
	}
	
	@Override
	public Object clean(String[] value, Map<String, String> errors) {
		if (value == null || value.length == 0) {
			return clean("", errors);
		}

		Object myValue = clean(value[0], errors);
		
		if (myValue == null || (myValue instanceof String && StringUtils.isBlank((String)myValue))) {
			return myValue; // super should have flagged errors,  and cleaned correctly
		}
		Map<Long,String> localChoices = getChoices();
		if (localChoices == null)   {
			errors.put(this.name, NO_CHOICES_ERROR);
		} else if (localChoices.containsKey(myValue.toString())) {
			return myValue;
		} else if (localChoices.containsKey(myValue)) {
			return myValue;
		}
		
		errors.put(this.name, UNKNOWN_CHOICE_ERROR);
		return myValue;
	}

}
